//
//  HXDPlusTextView.swift
//  weibo
//
//  Created by huxuedong on 15/12/14.
//  Copyright © 2015年 huxuedong. All rights reserved.
//

import UIKit

@IBDesignable class HXDPlusTextView: UITextView {
    
    private lazy var placeholderLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 0
        label.text = "占位文字"
        label.font = UIFont.systemFontOfSize(11)
        label.textColor = UIColor.lightGrayColor()
        return label
    }()
    
    @IBInspectable var placeholder: String? {
        didSet {
            placeholderLabel.text = placeholder
        }
    }
    
    override var text: String? {
        didSet {
            //当textView.text中有输入时，隐藏placeholderLabel
            placeholderLabel.hidden = hasText()
        }
    }
    
    override var font: UIFont? {
        didSet {
            placeholderLabel.font = font
        }
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        addSubview(placeholderLabel)
        //取消自动布局
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
        //LessThanOrEqual：小于或者等于字体的宽度
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: .Width, relatedBy: NSLayoutRelation.LessThanOrEqual, toItem: self, attribute: .Width, multiplier: 1, constant: -10))
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textChanged", name: UITextViewTextDidChangeNotification, object: nil)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        placeholderLabel.x = 5
        placeholderLabel.y = 10
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    @objc private func textChanged() {
        placeholderLabel.hidden = hasText()
    }
    
}
